<template>
  <div class="eva_logo">
    <canvas ref="refLogo" :width="size" :height="size"></canvas>
  </div>
</template>

<script>
import { data } from './data'
const logoUrl = require('./eva_sprites.png')
export default {
  name: '',
  props: {
    size: {
      type: Number,
      default: 54
    }
  },
  data () {
    return {}
  },
  computed: {
    // ...mapGetters(['appConfig'])
  },
  created () {
  },
  mounted () {
    this.renderAnimationLogo()
  },
  beforeDestroy () {
  },
  methods: {
    preloadImage (url) {
      return new Promise((resolve) => {
        const img = new Image()
        img.onload = () => resolve(img)
        img.src = url
      })
    },

    async renderAnimationLogo () {
      const img = await this.preloadImage(logoUrl)
      const canvas = this.$refs.refLogo
      const ctx = canvas.getContext('2d')
      // const frames = data.frames
      let i = 0
      let o = {}
      const key = Object.keys(data.animations)[0]
      const list = data.animations[key]
      const len = list.length
      const width = data.sourceW
      const height = data.sourceH
      const ratio = 1

      canvas.style.width = `${this.size}px`
      canvas.style.height = `${this.size}px`

      canvas.width = width * ratio
      canvas.height = height * ratio
      ctx.scale(ratio, ratio)

      var cacheCanvas = document.createElement('canvas')
      var ctxCache = cacheCanvas.getContext('2d')

      cacheCanvas.width = canvas.width
      cacheCanvas.height = canvas.height
      var timer = setInterval(function () {
        o = list[i]
        ctxCache.clearRect(0, 0, canvas.width, canvas.height)
        o = (Object.prototype.toString.call(o) === '[object Array]' ? o : [o])
        const dataSource = data
        for (var j = 0, t; j < o.length; j++) {
          t = dataSource.frames[o[j]]
          ctxCache.drawImage(
            img,
            t.x || dataSource.x || 0,
            t.y || dataSource.y || 0,
            t.width || dataSource.width,
            t.height || dataSource.height,
            t.offX || dataSource.offX || 0,
            t.offY || dataSource.offY || 0,
            t.width || dataSource.width,
            t.height || dataSource.height
          )
        }

        ctx.clearRect(0, 0, canvas.width, canvas.height)

        ctx.drawImage(cacheCanvas, 0, 0, canvas.width, canvas.height)
        i = ++i === len ? 0 : i

        if (i === 0) {
          // 停止动画--fix: 渲染进程内存一直在增加
          clearInterval(timer)
          timer = null
        }
      }, 40)
    }
  }
}
</script>

<style lang="scss" scoped>
.eva_logo {
  position: relative;
  z-index: 1;
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    display: block;
    width: 44px;
    height: 16px;
    background: linear-gradient(90deg, rgba(#7432ff, 0.5) 22.22%, rgba(#ec75ff, 0.5) 83.33%);
    opacity: 0.5;
    transform: translateX(-50%);
    filter: blur(8px);
    z-index: -1;
  }
}
</style>
